package com.mike.billingserver.controller.v1;

import com.mike.billingserver.dto.BillSearchDTO;
import com.mike.billingserver.form.BillForm;
import com.mike.billingserver.service.BillService;
import com.mike.billingserver.vo.KeyValueVO;
import com.mike.billingserver.vo.YearVO;
import common.lib.core.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.time.LocalDate;

/**
 * @author xiaozefeng
 * @date 12/12/18 1:29 PM
 */
@Controller
@RequestMapping("/v1/bills")
@Slf4j
public class BillController {


    @Autowired
    private BillService billService;

    /**
     * 添加账目
     * @param billForm
     * @param bindingResult
     * @return
     */
    @PostMapping
    @ResponseBody
    public ResultVO createBill(@Valid @RequestBody BillForm billForm, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultVO.error(bindingResult.getFieldError().getDefaultMessage());
        }
        BillForm result = billService.createBill(billForm);
        return ResultVO.ok(result);
    }

    /**
     * 账目查询页面
     * @param model
     * @param pageable
     * @param year
     * @param month
     * @param purpose
     * @return
     */
    @GetMapping
    public String list(Model model, @PageableDefault(page = 0, size = 100) Pageable pageable,
                       @RequestParam(value = "year", required = false) Integer year,
                       @RequestParam(value = "month", required = false) Integer month,
                       @RequestParam(value = "purpose", required = false, defaultValue = "") String purpose) {
        LocalDate now = LocalDate.now();
        int thisYear = now.getYear();
        if (year == null) {
            year = thisYear;
        }
        if (month == null) {
            month = now.getMonth().getValue();
        }
        log.info("year=[{}], month=[{}], purpose=[{}]", year, month, purpose);
        model.addAttribute("billPage", billService.findAll(pageable, new BillSearchDTO(year, month, purpose)));
        model.addAttribute("year", year);
        model.addAttribute("month", month);
        model.addAttribute("purpose", purpose);
        model.addAttribute("years", YearVO.generateYear());
        model.addAttribute("months", KeyValueVO.generateMonth());
        return "list";
    }

}
